import React, { PureComponent } from 'react';
import { Card, Form, Icon, Button, message } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import lodash from 'lodash';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import JobBasicConfigAdd from './components/JobBasicConfigAdd';
import MetricConfigAdd from './components/MetricConfigAdd';
import NotificationConfigAdd from './components/NotificationConfigAdd';
import { NotificationTypeMapper } from '../../utils/enum';
// import classNames from 'classnames';
// import styles from './JobAdd.less'

@connect(({ JobModel, loading }) => ({
  JobModel,
  quetyLoading: loading.effects['JobModel/queryPage'],
  addJobLoading: loading.effects['JobModel/addJob'],
}))
@Form.create()
export default class JobAdd extends PureComponent {

  state = {
    tabList: [
      { key: 'basic', tab: '基本配置', type: 'static' },
      { key: 'metric', tab: '监控项', type: 'static' },
      { key: 'notification', tab: '告警通知', type: 'static' },
      { key: 'document', tab: (<span><Icon type="info-circle" theme="outlined" />参考文档</span>), type: 'static' },
    ],
    tabActiveKey: "basic",
  }

  // 数据初始化
  componentDidMount() {
    // window.addEventListener('resize', this.handleHeight);
    // const { match: { params } } = this.props;
    // dispatch({ type: 'JobModel/findAllJob' });
    // console.log(params)
  }

  // 基本
  getBasicConfig = () => {
    const { JobModel: { addJobConfigData } } = this.props;
    return (
      <JobBasicConfigAdd
        jobConfigData={addJobConfigData}
        saveForm={form => { this.basicForm = form }}
      />
    );
  }

  // 监控项
  getMetricConfig = () => {
    const { dispatch, JobModel: { esMetricDataList } } = this.props;
    return (
      <MetricConfigAdd
        esMetricDataList={esMetricDataList}
        addEsMetricDataFunc={data => {
          const esMetricDataListNew = [...esMetricDataList, data];
          dispatch({ type: 'JobModel/save', payload: { esMetricDataList: esMetricDataListNew } });
        }}
        updateEsMetricDataFunc={data => {
          const index = lodash.findIndex(esMetricDataList, item => item.metricTitle === data.metricTitle);
          if (index !== -1) {
            const old = esMetricDataList[index];
            esMetricDataList[index] = { ...old, ...data };
            const esMetricDataListNew = [];
            lodash.forEach(esMetricDataList, item => esMetricDataListNew.push(item));
            dispatch({ type: 'JobModel/save', payload: { esMetricDataList: esMetricDataListNew } });
          }
        }}
        delEsMetricDataFunc={metricTitle => {
          const esMetricDataListNew = lodash.filter(esMetricDataList, item => item.metricTitle !== metricTitle);
          dispatch({ type: 'JobModel/save', payload: { esMetricDataList: esMetricDataListNew } });
        }}

        addExpectValueFunc={(metricTitle, expectValue) => {
          const esMetricDataIndex = lodash.findIndex(esMetricDataList, item => item.metricTitle === metricTitle);
          if (esMetricDataIndex !== -1) {
            const esMetricData = esMetricDataList[esMetricDataIndex];
            if (!esMetricData.expectValues) {
              esMetricData.expectValues = [];
            }
            esMetricData.expectValues.push(expectValue);
            esMetricDataList[esMetricDataIndex] = esMetricData;
            const esMetricDataListNew = [...esMetricDataList];
            dispatch({ type: 'JobModel/save', payload: { esMetricDataList: esMetricDataListNew } });
          }
        }}
        updateExpectValueFunc={(metricTitle, expectValue) => {
          const esMetricDataIndex = lodash.findIndex(esMetricDataList, item => item.metricTitle === metricTitle);
          if (esMetricDataIndex !== -1) {
            const esMetricData = esMetricDataList[esMetricDataIndex];
            if (esMetricData.expectValues) {
              const expectValueIndex = lodash.findIndex(esMetricData.expectValues, item => item.title === expectValue.title);
              if (expectValueIndex !== -1) {
                esMetricData.expectValues[expectValueIndex] = expectValue;
                esMetricDataList[esMetricDataIndex] = esMetricData;
                const esMetricDataListNew = [...esMetricDataList];
                dispatch({ type: 'JobModel/save', payload: { esMetricDataList: esMetricDataListNew } });
              }
            }
          }
        }}
        delExpectValueFunc={(metricTitle, title) => {
          const esMetricDataIndex = lodash.findIndex(esMetricDataList, item => item.metricTitle === metricTitle);
          if (esMetricDataIndex !== -1) {
            const esMetricData = esMetricDataList[esMetricDataIndex];
            const expectValues = lodash.filter(esMetricData.expectValues, item => item.title !== title);
            esMetricData.expectValues = expectValues;
            esMetricDataList[esMetricDataIndex] = esMetricData;
            const esMetricDataListNew = [...esMetricDataList];
            dispatch({ type: 'JobModel/save', payload: { esMetricDataList: esMetricDataListNew } });
          }
        }}
      />
    );
  }

  // 告警通知
  getNotificationConfig = () => {
    const { dispatch, JobModel: { notificationConfigList } } = this.props;
    return (
      <NotificationConfigAdd
        notificationConfigList={notificationConfigList}
        addNotificationConfigFunc={data => {
          const notificationConfigListNew = [...notificationConfigList, data];
          dispatch({ type: 'JobModel/save', payload: { notificationConfigList: notificationConfigListNew } });
        }}
        updateNotificationConfigFunc={(notificationType, templateId, data) => {
          const index = lodash.findIndex(notificationConfigList, { notificationType, templateId });
          if (index !== -1) {
            notificationConfigList[index] = data;
            const notificationConfigListNew = [...notificationConfigList];
            dispatch({ type: 'JobModel/save', payload: { notificationConfigList: notificationConfigListNew } });
          }
        }}
        delNotificationConfigFunc={(notificationType, templateId) => {
          const notificationConfigListNew = lodash.filter(notificationConfigList, item => item.notificationType !== notificationType && item.templateId !== templateId);
          dispatch({ type: 'JobModel/save', payload: { notificationConfigList: notificationConfigListNew } });
        }}
      />
    );
  }

  // 保存
  saveJob = () => {
    const { dispatch, JobModel: { esMetricDataList, notificationConfigList } } = this.props;
    this.basicForm.validateFields((err, formValues) => {
      if (err) {
        this.setState({ tabActiveKey: 'basic' });
        message.error('基本配置不完整');
        return;
      }
      if (!esMetricDataList || esMetricDataList.length <= 0) {
        this.setState({ tabActiveKey: 'metric' });
        message.error('未配置监控项，至少配置一个');
        return;
      }
      for (let i = 0; i < esMetricDataList.length; i++) {
        const { expectValues, metricTitle } = esMetricDataList[i];
        if (!expectValues || expectValues.length <= 0) {
          this.setState({ tabActiveKey: 'metric' });
          message.error(`监控项[${metricTitle}]未配置预期响应结果，至少配置一个`);
          return;
        }
      }
      if (!notificationConfigList || notificationConfigList.length <= 0) {
        this.setState({ tabActiveKey: 'notification' });
        message.error('未配置告警通知项，至少配置一个');
        return;
      }
      for (let i = 0; i < notificationConfigList.length; i++) {
        const { targetList, notificationType, templateId } = notificationConfigList[i];
        if (!targetList || targetList.length <= 0) {
          let notificationTypeLable = NotificationTypeMapper[notificationType];
          if (!notificationTypeLable) notificationTypeLable = NotificationTypeMapper.error;
          this.setState({ tabActiveKey: 'notification' });
          message.error(`告警通知项[${notificationTypeLable.lable}-${templateId}]未配置通知对象，至少配置一个`);
          return;
        }
      }
      // 调用保存操作
      const payload = {};
      payload.name = formValues.name;
      payload.cron = formValues.cron;
      payload.description = formValues.description;
      payload.esMetricDataList = esMetricDataList;
      payload.notificationRule = {
        rule: formValues.rule,
        frequencyTimeLength: formValues.frequencyTimeLength,
        frequencyCountMax: formValues.frequencyCountMax,
        flatlineTimeLengthMax: formValues.flatlineTimeLengthMax,
      };
      payload.notificationConfigList = notificationConfigList;
      dispatch({
        type: 'JobModel/addJob',
        payload,
        successCallBack: result => {
          message.success(`新增告警成功 -> ${result.alertConfig.name}`);
          dispatch(routerRedux.push('/alarm/job/:list'));
        },
      });
    });
  }

  render() {
    const { tabList, tabActiveKey } = this.state;
    const { dispatch, addJobLoading } = this.props;
    return (
      <PageHeaderLayout
        logo={(<Icon type="alert" theme="twoTone" style={{ fontSize: '26px' }} />)}
        title="新增告警-(告警配置)"
        tabList={tabList}
        tabActiveKey={tabActiveKey}
        onTabChange={key => this.setState({ tabActiveKey: key })}
        action={
          (
            <div>
              <Button.Group>
                <Button onClick={() => dispatch(routerRedux.push('/alarm/job/:list'))}>取消</Button>
              </Button.Group>
              <Button type="primary" onClick={this.saveJob} loading={addJobLoading} style={{ marginLeft: 16 }}>新增</Button>
            </div>
          )
        }
      >
        <Card bordered={false}>
          <div style={{ display: (tabActiveKey === "basic") ? undefined : 'none' }}>
            {this.getBasicConfig()}
          </div>
          <div style={{ display: (tabActiveKey === "metric") ? undefined : 'none' }}>
            {this.getMetricConfig()}
          </div>
          <div style={{ display: (tabActiveKey === "notification") ? undefined : 'none' }}>
            {this.getNotificationConfig()}
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
